package com.gwlc.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gwlc.common.config.LuckyConfig;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>lucky-com.gwlc.common.util-TokenTool</p>
 * <p>Description:  </p>
 * <p>Copyright: Copyright (c) 2021</p>
 * <p>Company: hanchunit@163.com</p>
 *
 * @author hanchun
 * @version 1.0
 * @date
 */


public class TokenTool {

    /**
     * 添加数据并创建token
     *
     * @param map
     * @return token
     */
    public static String createToken(Map<String, Object> map) {

        map.put("uuid", UUID.randomUUID().toString().replace("-", ""));
        byte[] bytes = map.toString().getBytes(StandardCharsets.UTF_8);
        return Base64.getUrlEncoder().encodeToString(bytes);
    }

    /**
     * 创建token
     *
     * @return token
     */
    public static String createToken() {
        byte[] bytes = UUID.randomUUID().toString().replace("-", "").getBytes(StandardCharsets.UTF_8);
        return Base64.getUrlEncoder().encodeToString(bytes);
    }

    /**
     * 创建token
     *
     * @param username 用户名
     * @return token
     */
    public static String createToken(String username) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = new HashMap<>(16);
        map.put("username", username);

        //token为用户名+用户超时时间
        map.put("outTime", System.currentTimeMillis() + LuckyConfig.getOutTime());
        byte[] bytes = objectMapper.writeValueAsString(map).getBytes(StandardCharsets.UTF_8);
        return Base64.getUrlEncoder().encodeToString(bytes);
    }

    /**
     * 解析token
     *
     * @param token token
     * @return 数据
     */
    public static String decodeToken(String token) {
        return new String(Base64.getUrlDecoder().decode(token));
    }


    /**
     * 解析token
     *
     * @param token token
     * @return 数据
     */
    public static Map<?, ?> decodeTokenMap(String token) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        String value = new String(Base64.getUrlDecoder().decode(token));


        return mapper.readValue(value, Map.class);
    }


}
